# -*- coding: UTF-8 -*-
import os

from flask import Flask, request, jsonify, json
from flask_cors import CORS

from modes import Hosts, scripts, db, options
from ssh import ssh

app = Flask(__name__)
db.init_app(app)
CORS(app)
app.config['SECRET_KEY'] = os.urandom(24)
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://root:123456@127.0.0.1:3306/sshmanage'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True


@app.route('/index')
def hello_world():
    db.create_all()
    add1 = Hosts(hostname="hostname1", ipaddr="127.0.0.1", port="22", username="root", passwd="123456")
    db.session.add(add1)
    db.session.commit()
    return 'Hello World!'


@app.route('/script', methods=['GET', 'POST'])
def script():
    if request.method == 'GET':
        allscript = scripts.query.all()
        scripts_output = []
        for sc in allscript:
            scripts_output.append(sc.to_json())
        return jsonify(scripts_output)
    else:
        try:
            fdata = request.form
            fdata1 = fdata.to_dict()
            addsc1 = scripts(scriptname=fdata1['scname'], scripts=fdata1['script'], desc=fdata1['desc'])
            db.session.add(addsc1)
            db.session.commit()
        except:
            db.session.rollback()
            return "fail"
        else:
            return "1"


@app.route('/system', methods=['GET', 'POST'])
def system():
    if request.method == 'GET':
        allopttions = options.query.all()
        optdata = []
        for opt in allopttions:
            optdata.append(opt.to_json())
        return jsonify(optdata)
    else:
        try:
            addinfo = json.loads(request.get_data(as_text=True))
            add1 = Hosts(hostname=addinfo['hostname'], Groups=addinfo['Groups'], ipaddr=addinfo['ipaddr'],
                         port=addinfo['port'], username=addinfo['username'], passwd=addinfo['pwd'],
                         check=addinfo['check'], Desc=addinfo['desc'])
            db.session.add(add1)
            db.session.commit()
            return jsonify("1")
        except:
            db.session.rollback()
            return "0"


@app.route('/runscript', methods=['GET', 'POST'])
def runscript():
    if request.method == 'GET':
        devicegroup = request.args.get('devicegroup')
        sctemplates = request.args.get('sctemplates')
        if devicegroup:
            dbdevicelists = Hosts.query.filter_by(Groups=devicegroup).all()
            dlist = []
            for device in dbdevicelists:
                dlist.append(device.to_json())
            return jsonify(dlist)
        elif sctemplates:
            resultscript = scripts.query.filter_by(id=sctemplates).all()
            sclist = []
            for sc in resultscript:
                sclist.append(sc.to_json())
            return jsonify(sclist)
        else:
            allscripts = scripts.query.all()
            sclists = []
            for sc in allscripts:
                sclists.append(sc.to_json())
            return jsonify(sclists)
            return jsonify("fail")
    else:
        sc = request.form
        resultinfo = []
        resultinfo.clear()
        shell = sc.getlist('shell')
        shell = "".join(shell)  # 转换成字符串
        hosts = (sc.getlist('host'))  # 转换成列表
        for host in hosts:
            hostinfo = Hosts.query.filter(Hosts.ipaddr == host).first()
            ip = hostinfo.ipaddr
            port = hostinfo.port
            username = hostinfo.username
            passwd = hostinfo.passwd
            hostresult = ssh(ip=ip, username=username, passwd=passwd, shell=shell, port=port)
            resultinfo.append(hostresult)
        return jsonify(resultinfo)


if __name__ == '__main__':
    app.run()
